import time


class InvalidSystemClock(Exception):
    """
    时钟回拨异常
    """
    pass


# 64位ID的划分
WORKER_ID_BITS = 5
DATACENTER_ID_BITS = 5
SEQUENCE_BITS = 12

# 最大取值计算
MAX_WORKER_ID = -1 ^ (-1 << WORKER_ID_BITS)  # 2**5-1 0b11111
MAX_DATACENTER_ID = -1 ^ (-1 << DATACENTER_ID_BITS)

# 移位偏移计算
WOKER_ID_SHIFT = SEQUENCE_BITS
DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS
TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS

# 序号循环掩码
SEQUENCE_MASK = -1 ^ (-1 << SEQUENCE_BITS)

# 开始时间截 (2015-01-01)
TWEPOCH = 1704038400000

class IdWorker(object):
    """
    用于生成IDs
    """

    def __init__(self, datacenter_id, worker_id, sequence=0):
        """
        初始化
        :param datacenter_id: 数据中心（机器区域）ID
        :param worker_id: 机器ID
        :param sequence: 其实序号
        """
        # sanity check
        if worker_id > MAX_WORKER_ID or worker_id < 0:
            raise ValueError('worker_id值越界')

        if datacenter_id > MAX_DATACENTER_ID or datacenter_id < 0:
            raise ValueError('datacenter_id值越界')

        self.worker_id = worker_id
        self.datacenter_id = datacenter_id
        self.sequence = sequence

        self.last_timestamp = -1  # 上次计算的时间戳

    def _gen_timestamp(self):
        """
        生成整数时间戳
        :return:int timestamp
        """
        return int(time.time() * 1000)

    def get_id(self, type):
        """
        获取新ID
        :return:
        """
        timestamp = self._gen_timestamp()

        # 时钟回拨
        if timestamp < self.last_timestamp:
            raise InvalidSystemClock

        if timestamp == self.last_timestamp:
            self.sequence = (self.sequence + 1) & SEQUENCE_MASK
            if self.sequence == 0:
                timestamp = self._til_next_millis(self.last_timestamp)
        else:
            self.sequence = 0

        self.last_timestamp = timestamp

        new_id = ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | (self.datacenter_id << DATACENTER_ID_SHIFT) | \
                 (self.worker_id << WOKER_ID_SHIFT) | self.sequence
        if type == 'str':
            return str(new_id)
        if type == 'int':
            return new_id

    def _til_next_millis(self, last_timestamp):
        """
        等到下一毫秒
        """
        timestamp = self._gen_timestamp()
        while timestamp <= last_timestamp:
            timestamp = self._gen_timestamp()
        return timestamp


worker = IdWorker(0, 1)
# print(len(worker.get_id('str')))

# import time
#
# class Snowflake:
#     def __init__(self, worker_id, epoch=1704038400000):
#         self.worker_id = worker_id
#         self.epoch = epoch
#         self.sequence = 0
#         self.last_timestamp = -1
#
#         # 根据worker_id位数计算最大序列号
#         self.max_sequence = -1 ^ (-1 << 12)
#
#     def _current_timestamp(self):
#         # 获取当前时间戳（毫秒级）
#         return int(time.time() * 1000)
#
#     def _wait_next_millis(self, last_timestamp):
#         # 等待下一个毫秒
#         timestamp = self._current_timestamp()
#         while timestamp <= last_timestamp:
#             timestamp = self._current_timestamp()
#         return timestamp
#
#     def generate_id(self):
#         timestamp = self._current_timestamp()
#
#         if timestamp < self.last_timestamp:
#             raise ValueError("Clock moved backwards. Refusing to generate id")
#
#         if timestamp == self.last_timestamp:
#             self.sequence = (self.sequence + 1) & self.max_sequence
#             if self.sequence == 0:
#                 timestamp = self._wait_next_millis(self.last_timestamp)
#         else:
#             self.sequence = 0
#
#         self.last_timestamp = timestamp
#
#         # 根据Snowflake算法生成ID
#         id = ((timestamp - self.epoch) << 22) | (self.worker_id << 12) | self.sequence
#         return id
#
# # 示例用法
# if __name__ == "__main__":
#     # 假设有两台机器，分别使用 worker_id 0 和 1
#     snowflake_0 = Snowflake(worker_id=0)
#     snowflake_1 = Snowflake(worker_id=1)
#
#     # 生成一些唯一ID
#     for _ in range(5):
#         print("Worker 0 ID:", snowflake_0.generate_id())
#         print("Worker 1 ID:", snowflake_1.generate_id())
